package com.jfblog.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 过滤留言内容中的特殊标签,防止xss,引自 开源项目：jflyfox
 * </p>
 * http://git.oschina.net/flyfox
 * 
 * @ClassName: HtmlUtil
 * @author Realfighter
 * @date 2015-5-21 上午11:56:52
 * 
 */
public class HtmlUtil {

	private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
	private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
	private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

	/**
	 * 去除Html标签
	 * 
	 * @Title: delHTMLTag
	 * @author Realfighter
	 * @param htmlStr
	 * @return
	 */
	public static String delHTMLTag(String htmlStr) {
		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll(""); // 过滤script标签

		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll(""); // 过滤style标签

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll(""); // 过滤html标签

		return htmlStr.trim(); // 返回文本字符串
	}

	/**
	 * 修改标签特殊字符
	 * 
	 * @Title: changeTag
	 * @author Realfighter
	 * @param content
	 * @return
	 */
	public static String changeTag(String content) {
		content = content.replaceAll("&", "&amp;");
		content = content.replaceAll("<", "&lt;");
		content = content.replaceAll(">", "&gt;");
		content = content.replaceAll("\"", "&quot;");
		content = content.replaceAll("'", "&#x27;");
		content = content.replaceAll("/", "&#x2f;");
		return content;
	}
}
